import { BaseGeometry } from './basegeometry';
import { Point } from './point';
import { GUtils } from './gutils';

export class RectGeometry extends BaseGeometry {
    constructor(x: number, y: number, width: number, height: number) {
        super(x, y, width, height);
    }
    /**
     * 判断是否落在形状内
     * @param point 
     */
    public pointInThis(point: Point): boolean {
        return this.bounds.pointInRect(point);
    }
    /**
     * 计算线段与此几何图形的焦点
     * @param ptStart 
     * @param ptEnd 
     */
    public getIntersectPoints(ptStart: Point, ptEnd: Point): Point[] {
        let pi1: Point|null = null, pi2: Point | null = null;
        let p1 = new Point(this.x, this.y);
        let p2 = new Point(this.x + this.width, this.y);
        const pIntersect = new Point();
        if (GUtils.getIntersectPoint(p1, p2, ptStart, ptEnd, pIntersect)) {
            pi1 = new Point(pIntersect.x, pIntersect.y);
        }
        p1 = new Point(this.x + this.width, this.y);
        p2 = new Point(this.x + this.width, this.y + this.height);
        if (GUtils.getIntersectPoint(p1, p2, ptStart, ptEnd, pIntersect)) {
            if (!pi1) {
                pi1 = new Point(pIntersect.x, pIntersect.y);
            } else {
                if (pIntersect.x !== pi1.x && pIntersect.y !== pi1.y) {
                    pi2 = new Point(pIntersect.x, pIntersect.y);
                }
            }
        }
        if (pi1 && pi2) {
            return [pi1, pi2];
        }
        p1 = new Point(this.x + this.width, this.y + this.height);
        p2 = new Point(this.x, this.y + this.height);
        if (GUtils.getIntersectPoint(p1, p2, ptStart, ptEnd, pIntersect)) {
            if (!pi1) {
                pi1 = new Point(pIntersect.x, pIntersect.y);
            } else {
                if (pIntersect.x !== pi1.x && pIntersect.y !== pi1.y) {
                    pi2 = new Point(pIntersect.x, pIntersect.y);
                }
            }
        }
        if (pi1 && pi2) {
            return [pi1, pi2];
        }
        p1 = new Point(this.x, this.y + this.height);
        p2 = new Point(this.x, this.y);
        if (GUtils.getIntersectPoint(p1, p2, ptStart, ptEnd, pIntersect)) {
            if (!pi1) {
                pi1 = new Point(pIntersect.x, pIntersect.y);
            } else {
                if (pIntersect.x !== pi1.x && pIntersect.y !== pi1.y) {
                    pi2 = new Point(pIntersect.x, pIntersect.y);
                }
            }
        }
        if (pi1 || pi2) {
            if (pi1 && pi2) {
                return [pi1, pi2];
            } else if (pi1) {
                return [pi1];
            } else if (pi2) {
                return [pi2];
            }
        }
        return [];
    }
}